<template>
    <view class="agriculture-container">
        <page-header title="农事日历" :showBack="false">
            <template #right>
                <!-- 这里放置右侧的自定义内容，比如按钮、图标等 -->
                <view class="to-add" v-if="isManager" @click="addNewTask">
                    <span>+</span>
                    新增
                </view>
            </template>
        </page-header>

        <!-- 日历部分 -->
        <view class="calendar-section">
            <view class="month-selector">
                <view class="arrow-left" @click="changeMonth(-1)">
                    <roc-icon-plus
                        type="fas"
                        name="angle-left"
                        :size="20"
                        color="#333"></roc-icon-plus>
                </view>
                <text class="month-display">{{ currentYear }}年{{ currentMonth }}月</text>
                <view class="arrow-right" @click="changeMonth(1)">
                    <roc-icon-plus
                        type="fas"
                        name="angle-right"
                        :size="20"
                        color="#333"></roc-icon-plus>
                </view>
            </view>

            <view class="weekday-header">
                <text v-for="(day, index) in weekdays" :key="index" class="weekday">{{ day }}</text>
            </view>

            <view class="calendar-days">
                <view
                    v-for="(day, index) in calendarDays"
                    :key="index"
                    class="day-item"
                    :class="{
                        'other-month': !day.currentMonth,
                        today: day.isToday,
                        'has-task': day.hasTasks,
                        selected:
                            selectedDate && day.date === selectedDate.date && day.currentMonth,
                    }"
                    @click="selectDate(day)">
                    <text class="day-number">{{ day.day }}</text>
                    <view v-if="day.hasTasks" class="task-indicator"></view>
                </view>
            </view>
        </view>

        <!-- 农事安排部分 -->
        <view class="task-section">
            <view class="task-header">
                <text class="task-title">{{ selectedDateDisplay }} 农事安排</text>
                <text class="view-all" @click="viewAllTasks">查看全部安排 ></text>
            </view>

            <view class="task-list">
                <template v-if="filteredScheduleList.length > 0">
                    <view
                        class="task-item"
                        v-for="(task, index) in filteredScheduleList"
                        :key="index">
                        <view class="task-icon">
                            <image
                                src="@/static/images/task-icon.png"
                                mode="widthFix"
                                style="width: 100%; height: 100%"></image>
                        </view>
                        <view class="task-info">
                            <text class="task-name">{{ task.name }}</text>
                            <text class="task-detail">
                                {{ task.plotName || '' }}-{{ task.fieldInfo }} ·
                                {{ task.responsiblePerson }}
                            </text>
                            <view class="task-status" :class="['status-' + task.status]">
                                {{ statusMap[task.status] }}
                            </view>
                        </view>
                    </view>
                </template>
                <template v-else>
                    <EmptyData />
                </template>
            </view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import { getFarmingSchedulePage } from '@/utils/api/farmingSchedule.js'
import { farmingSchedule } from '@/utils/api/index.js'
import EmptyData from '@/components/EmptyData/index.vue'
import { mapState, mapGetters } from 'vuex'
import {
    AGRICULTURAL_WORK_TYPES,
    STATUS_DICT,
    getDictText,
    AGRICULTURAL_WORK_TYPES_CHART,
} from '@/utils/dict.js'

export default {
    components: {
        PageHeader,
        EmptyData,
    },
    data() {
        return {
            AGRICULTURAL_WORK_TYPES_CHART,
            weekdays: ['日', '一', '二', '三', '四', '五', '六'],
            currentYear: new Date().getFullYear(),
            currentMonth: new Date().getMonth() + 1,
            selectedDate: null,
            calendarDays: [],
            currentTasks: [], // 页面不再使用，改为 scheduleList
            scheduleList: [],
            total: 0,
            // 定义状态映射
            statusMap: {
                0: '未完成',
                1: '部分完成',
                2: '已经完成',
            },
        }
    },
    computed: {
        ...mapGetters(['isManager']),
        selectedDateDisplay() {
            if (!this.selectedDate) {
                return new Date().getMonth() + 1 + '月' + new Date().getDate() + '日'
            }
            return this.selectedDate.month + '月' + this.selectedDate.day + '日'
        },
        filteredScheduleList() {
            if (!this.selectedDate) return this.scheduleList
            const { year, month, day } = this.selectedDate
            // 构造 yyyy-mm-dd 字符串
            const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(
                2,
                '0'
            )}`
            return this.scheduleList.filter((item) => {
                // 任务的日期格式假设为 yyyy-mm-dd
                if (!item.startDate) return false
                // 只显示当天的任务
                return item.startDate <= dateStr && item.endDate >= dateStr
            })
        },
    },
    onShow() {
        this.fetchSchedule({ page: 1, size: 99 }) // 根据实际参数调整
    },
    created() {
        this.initCalendar()
        // 默认选中今天
        const today = new Date()
        this.selectedDate = {
            year: today.getFullYear(),
            month: today.getMonth() + 1,
            day: today.getDate(),
            date: today.getDate(),
            currentMonth: true,
            isToday: true,
            hasTasks: true,
        }
    },
    methods: {
        initCalendar() {
            const year = this.currentYear
            const month = this.currentMonth

            // 获取当月第一天是星期几
            const firstDay = new Date(year, month - 1, 1).getDay()
            // 获取当月天数
            const daysInMonth = new Date(year, month, 0).getDate()
            // 获取上个月天数
            const daysInPrevMonth = new Date(year, month - 1, 0).getDate()

            const days = []
            const today = new Date()
            const todayDate = today.getDate()
            const todayMonth = today.getMonth() + 1
            const todayYear = today.getFullYear()

            // 检查日期是否有任务的函数
            const checkHasTasks = (year, month, day) => {
                const currentDate = `${year}-${String(month).padStart(2, '0')}-${String(
                    day
                ).padStart(2, '0')}`
                return this.scheduleList.some((task) => {
                    return task.startDate <= currentDate && task.endDate >= currentDate
                })
            }

            // 上个月的日期
            for (let i = firstDay - 1; i >= 0; i--) {
                const day = daysInPrevMonth - i
                const prevMonth = month - 1
                const prevYear = prevMonth === 0 ? year - 1 : year
                const actualMonth = prevMonth === 0 ? 12 : prevMonth
                days.push({
                    day,
                    date: day,
                    currentMonth: false,
                    isToday: false,
                    hasTasks: checkHasTasks(prevYear, actualMonth, day),
                })
            }

            // 当月的日期
            for (let i = 1; i <= daysInMonth; i++) {
                days.push({
                    day: i,
                    date: i,
                    currentMonth: true,
                    isToday: i === todayDate && month === todayMonth && year === todayYear,
                    hasTasks: checkHasTasks(year, month, i),
                })
            }

            // 下个月的日期
            const remaining = 42 - days.length
            for (let i = 1; i <= remaining; i++) {
                const nextMonth = month + 1
                const nextYear = nextMonth > 12 ? year + 1 : year
                const actualMonth = nextMonth > 12 ? 1 : nextMonth
                days.push({
                    day: i,
                    date: i,
                    currentMonth: false,
                    isToday: false,
                    hasTasks: checkHasTasks(nextYear, actualMonth, i),
                })
            }

            this.calendarDays = days
        },
        changeMonth(offset) {
            let newMonth = this.currentMonth + offset
            let newYear = this.currentYear

            if (newMonth > 12) {
                newMonth = 1
                newYear++
            } else if (newMonth < 1) {
                newMonth = 12
                newYear--
            }

            this.currentMonth = newMonth
            this.currentYear = newYear
            this.initCalendar()
        },
        selectDate(day) {
            if (day.currentMonth) {
                this.selectedDate = {
                    ...day,
                    year: this.currentYear,
                    month: this.currentMonth,
                }
                // 这里可以加载该日期的任务
            }
        },
        viewAllTasks() {
            console.log('isManager', this.isManager)
            if (this.isManager) {
                uni.navigateTo({
                    url: '/pages/my/taskManage/taskManagement?isManager=1',
                })
            } else {
                uni.navigateTo({
                    url: '/pages/my/task/task?isManager=0',
                })
            }
        },
        addNewTask() {
            uni.navigateTo({
                url: '/pages/my/taskManage/addTask',
            })
        },
        navigateTo(url) {
            uni.navigateTo({
                url: url,
            })
        },
        async fetchSchedule(params) {
            console.log('获取')
            const res = await farmingSchedule.getFarmingSchedulePage(params)
            console.log('返回的数据')
            if (res.code === 0) {
                this.scheduleList = res.data.list.map((item) => ({
                    name: AGRICULTURAL_WORK_TYPES[item.workTask] || '未命名任务',
                    plotName: item.plotName,
                    fieldInfo: item.fieldName,
                    responsiblePerson: item.personInCharge || '',
                    status: item.status ?? 0, // 状态 0/1/2 未完成/部分完成/已经完成
                    startDate: item.startDate,
                    endDate: item.endDate,
                }))
                this.total = res.data.total
                // 重新初始化日历以更新任务指示器
                this.initCalendar()
            } else {
                uni.showToast({ title: res.msg || '获取数据失败', icon: 'none' })
            }
        },
    },
}
</script>

<style lang="scss">
.agriculture-container {
    min-height: 100vh;
    background-color: #f5f5f5;

    .calendar-section {
        background-color: #fff;
        margin: 20rpx;
        border-radius: 12rpx;
        padding: 20rpx;

        .month-selector {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10rpx 0;

            .arrow-left,
            .arrow-right {
                padding: 10rpx;
            }

            .month-display {
                font-size: 28rpx;
                font-weight: 500;
            }
        }

        .weekday-header {
            display: flex;
            justify-content: space-around;
            padding: 20rpx 0;

            .weekday {
                width: calc(100% / 7);
                text-align: center;
                font-size: 26rpx;
                color: #666;
            }
        }

        .calendar-days {
            display: flex;
            flex-wrap: wrap;

            .day-item {
                width: calc(100% / 7);
                height: 80rpx;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                position: relative;

                .day-number {
                    font-size: 28rpx;
                    line-height: 1;
                }

                .task-indicator {
                    width: 8rpx;
                    height: 8rpx;
                    border-radius: 50%;
                    background-color: #2eb57d;
                    margin-top: 6rpx;
                }

                &.other-month {
                    color: #ccc;
                }

                &.today {
                    color: #2eb57d;
                    font-weight: bold;
                }

                &.selected {
                    background-color: #e8f7f1;
                    border-radius: 50%;
                }

                &.has-task .task-indicator {
                    display: block;
                }
            }
        }
    }

    .task-section {
        background-color: #fff;
        margin: 20rpx;
        border-radius: 12rpx;
        padding: 20rpx;

        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 20rpx;

            .task-title {
                font-size: 28rpx;
                font-weight: 500;
            }

            .view-all {
                font-family: OPPOSans, OPPOSans;
                font-weight: 500;
                font-size: 24rpx;
                color: #2e6140;
            }
        }

        .task-list {
            .task-item {
                display: flex;
                align-items: center;
                padding: 20rpx 0;
                border-bottom: 1px solid #f5f5f5;

                &:last-child {
                    border-bottom: none;
                }

                .task-icon {
                    width: 80rpx;
                    height: 80rpx;
                    background-color: #e8f7f1;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 20rpx;
                }

                .task-info {
                    flex: 1;

                    .task-name {
                        font-size: 28rpx;
                        font-weight: 500;
                        margin-bottom: 10rpx;
                        display: block;
                    }

                    .task-detail {
                        font-size: 24rpx;
                        color: #999;
                    }
                }

                .task-status {
                    padding: 6rpx 16rpx;
                    border-radius: 30rpx;
                    font-size: 24rpx;
                    background-color: #e3e3e3;
                    color: #333333;
                    width: fit-content;
                    &.status-0 {
                        background-color: #ffeaea;
                        color: #e74c3c;
                    }
                    &.status-1 {
                        background-color: #fff7e6;
                        color: #f39c12;
                    }
                    &.status-2 {
                        background-color: #e8f7f1;
                        color: #2eb57d;
                    }
                }
            }
        }
    }

    .add-button {
        position: fixed;
        right: 40rpx;
        bottom: 40rpx;
        width: 160rpx;
        height: 80rpx;
        background-color: #2eb57d;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        box-shadow: 0 6rpx 20rpx rgba(46, 181, 125, 0.3);

        text {
            font-size: 28rpx;
            margin-left: 10rpx;
        }
    }
}
.to-add {
    color: #fff;
    font-size: 36rpx;
    span {
        font-size: 40rpx;
        display: inline-block;
        margin-right: 5rpx;
    }
}
</style>
